<template>
	<coreshop-page title="代理商申请" mode="left">
		<view v-if="state.show">
			<view class="content">
				<uv-parse :content="shopConfigStore.config?.agentNotes"></uv-parse>
			</view>

			<coreshop-fixed-bottom-button v-if="state.info?.conditionStatus" @onClick="onShowSubmitApplyAgency()"
				title="申请"></coreshop-fixed-bottom-button>
			<coreshop-fixed-bottom-button v-else backgroundColor="#eee" title="您的条件暂不满足"></coreshop-fixed-bottom-button>


			<uv-popup ref="applyAgencyPopupRef" mode="bottom" :round="8" :closeOnClickOverlay="false" closeable
				bgColor="#eef2f6">
				<ApplyForm @submitApply="onSubmitApplyAgency()" />
			</uv-popup>
		</view>
	</coreshop-page>
</template>

<script setup lang="ts">
	import { reactive, ref } from 'vue';
	import { onLoad } from '@dcloudio/uni-app';
	import { queryAgentInfo, queryApplyAgent } from '@/core/api';
	import type { Response } from '@/core/models';
	import { handleShowToast, handleRouteRedirectTo } from '@/core/utils';
	import { AgentApplyStatus } from '@/core/enum';
	import ApplyForm from './apply-form.vue'
	import { useShopConfigStore, useUserInfoStore } from '@/core/store';

	/** 获取项目配置 */
	const shopConfigStore = useShopConfigStore();

	/** 获取 用户数据 */
	const userInfoStore = useUserInfoStore();

	const applyAgencyPopupRef = ref();

	const state = reactive<{
		info : any;
		show : boolean;
	}>({
		info: {},
		show: false,
	})
	onLoad(() => {
		getDistributionInfo();
	});

	/** 获取分销商进度状态 */
	const getDistributionInfo = async () => {
		const info : Response<any> = await queryAgentInfo({ check_condition: true });
		if (info.status) {
			state.info = info.data;
			if (info.data?.verifyStatus == AgentApplyStatus.success || (!info.data?.needApply && info.data?.conditionStatus)) {
				handleRouteRedirectTo('/pages/subpackage/agency/index/index');
			} else if (info.data?.verifyStatus > AgentApplyStatus.success) {
				handleRouteRedirectTo(`/pages/subpackage/agency/apply/state`);
			} else {
				state.show = true;
			}
		} else {
			handleShowToast(info.msg)
		}
	}

	const onShowSubmitApplyAgency = () => {
		applyAgencyPopupRef.value?.open();
	};

	/** 申请提交 */
	const onSubmitApplyAgency = async () => {
		const applyAgent : Response<any> = await queryApplyAgent({
			name: userInfoStore.userInfo?.nickName,
			weixin: userInfoStore.userInfo?.mobile,
			qq: userInfoStore.userInfo?.mobile,
			mobile: userInfoStore.userInfo?.mobile,
			agreement: "on",
		});
		if (applyAgent.status) {
			handleShowToast(applyAgent.msg, 'success', () => {
				setTimeout(() => {
					handleRouteRedirectTo(`/pages/subpackage/agency/apply/state`);
				}, 1500);
			})
		} else {
			handleShowToast(applyAgent.msg)
		}
	}
</script>

<style scoped lang="scss">
	.content {
		padding: 25rpx 25rpx 180rpx;
		border-radius: 15rpx;
		background-color: #ffffff;
		margin: 25rpx;
		font-size: 28rpx;
	}
</style>